package cn.t.listener.user;

import cn.t.user.event.UserRedisClearEvent;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * @author l
 */
@Slf4j
@Component
public class UserRedisClearListener implements ApplicationListener<UserRedisClearEvent> {


    @Async
    @Override
    public void onApplicationEvent(@NonNull UserRedisClearEvent event) {
        log.info("UserRedisClearEvent = {}", event);
        if (event.getRedisKey() == null || event.getRedisKey().length == 0) {
            return;
        }

        Arrays.stream(event.getRedisKey()).forEach(key -> {
            if (key.endsWith("*")) {
                redissonClient.getKeys().getKeysByPattern(key).forEach(aKey -> {
                    boolean result = redissonClient.getBucket(aKey).delete();
                    log.debug("{} is delete status = {}", aKey, result);
                });
            }
            boolean result = redissonClient.getBucket(key).delete();
            log.debug("{} is delete status = {}", key, result);
        });


    }

    @Autowired
    private RedissonClient redissonClient;
}
